<?php
class DownloadsController extends AppController {

	var $name = 'Downloads';
	var $uses = array('Download');
	var $components = array('SwfUpload');

	function beforeFilter() {
		parent::beforeFilter();
	}
	
	function index() {
		$this->Download->recursive = 0;
		$this->set('downloads', $this->paginate());
	}

	function view($file = null) {
		$file = $this->Download->findByFile($file); 
		if (empty($file)) {
			$this->Session->setFlash(__('FILE_NOT_FOUND', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->set('file',$file);
	}
	
	function get($file) {
		$name = $this->Download->findByFile($file,'file');
		if(!empty($name)) {
			$this->Download->updateAll(array('downloaded'=>'downloaded+1'),array('Download.file'=>$file));
			uses('file');
			$path = 'files'.DS.'downloads'.DS.$name['Download']['file'];
            //var_dump($path);
			$file =& new File($path);
			//$file->Folder->path=DS.'files'.DS.'downloads'.DS;
			//var_dump($file);
            $this->RequestHandler->respondAs('zip');
			echo $file->read();
		}
	}

	function admin_index() {
		$this->Download->recursive = 0;
		$this->set('downloads', $this->paginate());
	}

	function admin_add() {
		if(!empty($this->data)) {
			$this->SwfUpload->uploadpath = 'files' . DS . 'downloads' . DS;
			$this->SwfUpload->data['Download']['Filedata'] = $this->data['Download']['file'];
			
			if($this->SwfUpload->upload()) {
				$this->data = $this->Download->prepareFileData($this->data,$this->SwfUpload);
				$this->Download->create();
				if($this->Download->save($this->data)) {
					$this->Session->setFlash(__('FILE_SAVED_OK',true));
					$this->redirect(array('action'=>'index'));
				} else {
					$this->Session->setFlash(__('FILE_SAVED_ERROR',true));
				}
			} else {
				$this->Session->setFlash(__('FILE_SAVED_ERROR',true));
			}
		}
	}

	function admin_edit($id = null) {
		if (!$this->Download->findById($id)) {
			$this->Session->setFlash(__('FILE_NOT_FOUND', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Download->save($this->data)) {
				$this->Session->setFlash(__('FILE_SAVED_OK',true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('FILE_SAVED_ERROR',true));
			}
		} else {
			$this->data = $this->Download->read(null, $id);
		}
	}

	function admin_delete($id = null) {
		if (!$this->Download->findById($id)) {
			$this->Session->setFlash(__('FILE_NOT_FOUND', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Download->del($id)) {
			$this->Session->setFlash(__('FILE_DELETED_OK', true));
			
			uses('file');
			$name = $this->Download->findById($id,'file');
			$path = 'files'.DS.'downloads'.DS.$name['Download']['file'];
			$file =& new File($path);
			$file->delete();
		} else {
			$this->Session->setFlash(__('FILE_DELETED_ERROR', true));
		}
		$this->redirect(array('action'=>'index'));
	}

}
?>